import xml.sax
import commands
from core.models import *
from django.core.management import execute_manager

xml_file = "data.xml"

INDENT = "  "

class tagHandler(xml.sax.handler.ContentHandler):
  def __init__(self):
    self.tags = {}
  
  # handle the new coming element.
  def startElement(self, name, attrs):
    name = name.encode('ascii')
    if(name == "ext_service"):
      return
    if(name == "table"):
      table_name = attrs.getValue("name")
      self.table_name = table_name
      
    else:
      self.tags[name] = attrs.getValue("type")
      
  # write out the new Model to models.py
  def write_out_model(self):
    file_name = "core/models.py"
    output = open(file_name, "a")
    output.write("\n#Create automatically based on input XML\n")
    output.write("class " + self.table_name.title() + "(models.Model):\n")
    for field, field_type in self.tags.iteritems():
      output.write(INDENT + field + " = " + self.get_field_type(field_type) + "\n")
    output.close

  def add_new_db_entry(self):
    extend_table = ExtendTables(self.table_name, "")
    extend_table.save()

  # return the related content type, which needs to be written in the models.py
  def get_field_type(self, raw_type):
    type_string = "models."
    if(raw_type == "text"):
      return type_string + "CharField(max_length = 50)"
    elif(raw_type == "number"):
      return type_string + "IntegerField()"
    elif(raw_type == "bool"):
      return type_string + "BooleanField()"

  def sync_db(self):
    commands.getstatusoutput('python manager.py syncdb')

xml_parser = xml.sax.make_parser()
t_handler = tagHandler()

xml_parser.setContentHandler(t_handler)

xml_parser.parse(xml_file)

t_handler.write_out_model()
t_handler.add_new_db_entry()
